<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="bookName" label="书名">
				<uni-easyinput placeholder="选择所属书籍" v-model="formData.bookName" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="chapter" label="章节名">
				<uni-easyinput placeholder="章节名称" v-model="formData.chapter"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="content" label="内容">
				<view id="div1"> </view>
			</uni-forms-item>
			<uni-forms-item name="order" label="排序">
				<uni-easyinput placeholder="章节所属位置(如第一章则为0)" type="number" v-model="formData.order"></uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/chapter.js';
	import E from 'wangeditor'
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'chapter';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"bookName": "",
				"chapter": "",
				"content": "",
				"order": null
			}
			return {
				formData,
				bookList: [],
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				},
			}
		},
		onLoad(p) {
			this.formData.bookName = p.bookName
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
			this.onWangEdit()
		},
		methods: {
			onWangEdit() {
				var that = this
				const editor = new E('#div1');
				editor.customConfig = editor.customConfig ? editor.customConfig : editor.config;
				editor.customConfig.onchange = function(newHtml) {
					that.formData.content = newHtml
				};
				editor.config.customUploadImg = function(resultFiles, insertImgFn) {
					const file = resultFiles[0];
					const url = URL.createObjectURL(file)
					uniCloud.uploadFile({
						filePath: url,
						cloudPath: file.name,
						onUploadProgress: function(progressEvent) {
							var percentCompleted = Math.round(
								(progressEvent.loaded * 100) / progressEvent.total
							);
						},
						success: (res) => {
							insertImgFn(res.fileID)
						},
						fail: (error) => {
							console.log(error)
						}
					});
				}
				editor.create()
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection('book').where('name=="' + this.formData.bookName + '"').get().then((res) => {
					if (res.result.data.length == 1) {
						let list = res.result.data[0].list
						list[this.formData.order] = this.formData.chapter
						db.collection('book').where('_id=="' + res.result.data[0]._id + '"').update({
							list: list
						}).then((res) => {
							db.collection(dbCollectionName).add(value).then((res) => {
								uni.showToast({
									title: '新增成功'
								})
								this.getOpenerEventChannel().emit('refreshData')
								setTimeout(() => uni.navigateBack(), 500)
							})
						}).catch((err)=>{
							uni.showToast({
								icon:'none',
								title: '章节序号不正确'
							})
						})
					} else {
						uni.showToast({
							icon:"none",
							title: '未找到该书籍'
						})
					}

				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>
<style>
	#div1 {
		z-index: 0;
		position: relative;
	}
</style>